package com.insyte.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class BitmapUtility {
    public static void scaleImageWithOriRatito(ImageView view, int boundBoxInDp) {
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable) drawing).getBitmap();

        // Get current dimensions
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // Determine how much to scale: the dimension requiring less scaling is
        // closer to the its side. This way the image always stays inside your
        // bounding box AND either x/y axis touches it.
        float xScale = ((float) boundBoxInDp) / width;
        float yScale = ((float) boundBoxInDp) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        // Create a matrix for the scaling and add the scaling data
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        // Create a new bitmap and convert it to a format understood by the
        // ImageView
        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();

        // Apply the scaled bitmap
        view.setImageDrawable(result);

        // Now change ImageView's dimensions to match the scaled image
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view
                .getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }

    public static int dpToPx(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }

    public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input,
                                                int pixels, int w, int h, boolean squareTL, boolean squareTR,
                                                boolean squareBL, boolean squareBR) {

        Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final float densityMultiplier = context.getResources()
                .getDisplayMetrics().density;

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0 + 5, 0 + 5, w - 5, h - 5);
        final RectF rectF = new RectF(rect);

        // make sure that our rounded corner is scaled appropriately

        final float roundPx = pixels * densityMultiplier;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        // canvas.drawColor(Color.BLACK);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        // draw rectangles over the corners we want to be square
        if (squareTL) {
            canvas.drawRect(0, 0, w / 2, h / 2, paint);
        }
        if (squareTR) {
            canvas.drawRect(w / 2, 0, w, h / 2, paint);
        }
        if (squareBL) {
            canvas.drawRect(0, h / 2, w / 2, h, paint);
        }
        if (squareBR) {
            canvas.drawRect(w / 2, h / 2, w, h, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // paint.setXfermode(new AvoidXfermode(Color.WHITE, 255,
        // AvoidXfermode.Mode.TARGET));
        canvas.drawBitmap(input, 0, 0, paint);

        return output;
    }

    // public static Bitmap getRoundedCornerBitmap(Context context, Bitmap
    // bitmap,
    // float upperLeft, float upperRight, float lowerRight,
    // float lowerLeft, int endWidth, int endHeight) {
    // float densityMultiplier =
    // context.getResources().getDisplayMetrics().density;
    //
    // // scale incoming bitmap to appropriate px size given arguments and
    // // display dpi
    // bitmap = Bitmap.createScaledBitmap(bitmap,
    // Math.round(endWidth * densityMultiplier),
    // Math.round(endHeight * densityMultiplier), true);
    //
    // // create empty bitmap for drawing
    // Bitmap output = Bitmap.createBitmap(
    // Math.round(endWidth * densityMultiplier),
    // Math.round(endHeight * densityMultiplier), Config.ARGB_8888);
    //
    // // get canvas for empty bitmap
    // Canvas canvas = new Canvas(output);
    // int width = canvas.getWidth();
    // int height = canvas.getHeight();
    //
    // // scale the rounded corners appropriately given dpi
    // upperLeft *= densityMultiplier;
    // upperRight *= densityMultiplier;
    // lowerRight *= densityMultiplier;
    // lowerLeft *= densityMultiplier;
    //
    // Paint paint = new Paint();
    // paint.setAntiAlias(true);
    // paint.setColor(Color.WHITE);
    //
    // // fill the canvas with transparency
    // canvas.drawARGB(0, 0, 0, 0);
    //
    // // draw the rounded corners around the image rect. clockwise, starting
    // // in upper left.
    // canvas.drawCircle(upperLeft, upperLeft, upperLeft, paint);
    // canvas.drawCircle(width - upperRight, upperRight, upperRight, paint);
    // canvas.drawCircle(width - lowerRight, height - lowerRight, lowerRight,
    // paint);
    // canvas.drawCircle(lowerLeft, height - lowerLeft, lowerLeft, paint);
    //
    // // fill in all the gaps between circles. clockwise, starting at top.
    // RectF rectT = new RectF(upperLeft, 0, width - upperRight, height / 2);
    // RectF rectR = new RectF(width / 2, upperRight, width, height
    // - lowerRight);
    // RectF rectB = new RectF(lowerLeft, height / 2, width - lowerRight,
    // height);
    // RectF rectL = new RectF(0, upperLeft, width / 2, height - lowerLeft);
    //
    // canvas.drawRect(rectT, paint);
    // canvas.drawRect(rectR, paint);
    // canvas.drawRect(rectB, paint);
    // canvas.drawRect(rectL, paint);
    //
    // // set up the rect for the image
    // Rect imageRect = new Rect(0, 0, width, height);
    //
    // // set up paint object such that it only paints on Color.WHITE
    // paint.setXfermode(new AvoidXfermode(Color.WHITE, 255,
    // AvoidXfermode.Mode.TARGET));
    //
    // // draw resized bitmap onto imageRect in canvas, using paint as
    // // configured above
    // canvas.drawBitmap(bitmap, imageRect, imageRect, paint);
    //
    // return output;
    // }

    public static Bitmap createDrawableFromView(Context context, View view) {
        Bitmap bitmap = null;
        try {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
            view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
            view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
            view.buildDrawingCache();
            bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
        } catch (NullPointerException e) {
            Log.e("NullPointerException", e.toString());
            e.printStackTrace();
        }
        return bitmap;
    }

    public static Bitmap loadBitmap(String url) {
        Log.d("BitmapUtility", "Start Load Url : " + url);
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream());

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[16384];

            while ((nRead = in.read(data, 0, data.length)) != -1) {
                dataStream.write(data, 0, nRead);
            }

            dataStream.flush();

            final byte[] newData = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();

            bitmap = BitmapFactory.decodeByteArray(newData, 0, newData.length,
                    options);
        } catch (IOException e) {
            Log.e("My fault", "Could not load Bitmap from: " + url);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }

            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }

        return bitmap;
    }

}
